<!DOCTYPE>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>图层组控制</title>
    <link href='./css/bootstrap.min.css' rel='stylesheet' />
    <link href='./css/bootstrap-responsive.min.css' rel='stylesheet' />
    <link href="./css/zTreeStyle.css" rel="stylesheet"/>
    <style type="text/css">
        body{
            margin: 0;
            overflow: hidden;
            background: #fff;
        }
        #map{
            position: relative;
            height: 510px;
            border:1px solid #3473b7;
        }
        #toolbar {
            position: relative;
            padding-top: 5px;
            padding-bottom: 10px;
        }
        .win_bg{background:#CCC; opacity:0.2; filter:alpha(opacity=20); position:absolute; left:0px; top:0px; width:100%; height:100%; z-index:998;}
        .winTitle{background:#4192c9; height:20px; line-height:20px}
        .winTitle .title_left{font-weight:bold; color:#FFF; padding-left:5px; float:left}
        .winTitle .title_right{float:right; padding-right:3px;}
        .winTitle .title_right a{color:#FFF; text-decoration:none; padding-right:3px;}
        .winTitle .title_right a:hover{text-decoration:underline; color:#FF0000; padding-right:3px;}
        .transferPreference {
            border: 1px solid #D6E3F1;
            height: 20px;
            margin: 1px 30%;
            padding: 0 12px;
        }
        .winContent{padding:5px; overflow-y:auto; height:550px;}
        .popupWindow {
            right:20px;
            top:60px;
            position: absolute;
            border: 2px solid #D6E3F1;
            background: #FFF;
            z-index: 9999;
        }
    </style>
    <script src='../libs/SuperMap.Include.js'></script>
    <script src='./js/jquery.js'></script>
    <script src="./js/jquery.ztree.all.min.js"></script>
    <script type="text/javascript">
        var map = null;
        var layer = null;
        var url = null;
        var tempLayerID = null,
                host = document.location.toString().match(/file:\/\//)?"http://localhost:8090":'http://' + document.location.host,
                url =host+"/iserver/services/map-jingjin/rest/maps/京津地区地图";
        // 获取子图层状态信息
        function getLayersInfo() {
            var getLayersInfoService = new SuperMap.REST.GetLayersInfoService(url);
            getLayersInfoService.events.on({ "processCompleted": getLayersInfoCompleted});
            getLayersInfoService.processAsync();
        }

        //与服务器交互成功，得到子图层信息
        function getLayersInfoCompleted(getLayersInfoEventArgs) {
            if (getLayersInfoEventArgs.result) {
                {
                    handleTreeData(getLayersInfoEventArgs.result.subLayers.layers,1);
                    showWindow();
                    $.fn.zTree.init($("#tree"), setting, treeNodes);
                }
            }
            createTempLayer();
        }
        //图层组控制菜单的配置
        var setting = {
            view: {
                dblClickExpand: false,
                showLine: false,
                showIcon: false,
                selectedMulti: false
            },
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: "0"
                }
            },
            callback: {
                beforeClick: function(treeId, treeNode) {
                    var zTree = $.fn.zTree.getZTreeObj("tree");
                    if (treeNode.isParent) {
                        zTree.expandNode(treeNode);
                        return false;
                    }
                },
                onCheck: setLayerStatus
            }
        };

        var treeNodes = [];
        var layerID = 0;
        //处理layers中的子图层信息为 ztree所需的数据格式
        function handleTreeData(layers){
            var length = layers.length;
            for(var i = 0; i<length; i++){
                var node = {};
                node.id = i+1;
                node.pId = 0 ;
                node.name = layers[i].name;
                node.open = true;
                node.isChild = false;
                if(layers[i].visible){
                    node.checked = true;
                }
                treeNodes.push(node);

                if(layers[i].subLayers.layers && layers[i].subLayers.layers.length>0){
                    for(var j = 0; j< layers[i].subLayers.layers.length; j++){
                        var node = {};
                        node.id = (i+1)*10 + j;
                        node.pId = i+1 ;
                        node.name = layers[i].subLayers.layers[j].name;
                        node.isChild = true;
                        node.layerID = j;
                        layerID++;
                        if(layers[i].subLayers.layers[j].visible){
                            node.checked = true;
                        }
                        treeNodes.push(node);
                    }
                }
            }

        }

        //创建临时图层来初始化当前地图显示
        function createTempLayer() {
            //子图层控制参数必设：url、mapName、SetLayerStatusParameters
            var layerStatusParameters = new SuperMap.REST.SetLayerStatusParameters();
            layerStatusParameters = getLayerStatusList(layerStatusParameters);

            var setLayerStatusService = new SuperMap.REST.SetLayerStatusService(url);
            setLayerStatusService.events.on({ "processCompleted": createTempLayerCompleted});
            setLayerStatusService.events.on({ "processFailed": createTempLayerFailed});
            setLayerStatusService.processAsync(layerStatusParameters);
        }

        //获取当前地图子图层状态信息
        function getLayerStatusList(parameters) {
            for(var i = 0; i<treeNodes.length; i++){
                if(treeNodes[i].isChild){
                    var layerStatus = new SuperMap.REST.LayerStatus();
                    layerStatus.layerName = treeNodes[i].name;
                    layerStatus.isVisible = false;
                    parameters.layerStatusList.push(layerStatus);

                }
            }
            //设置资源在服务端保存的时间，单位为分钟，默认为10
            parameters.holdTime = 30;
            return parameters;
        }

        //与服务器交互成功，创建临时图层
        function createTempLayerCompleted(createTempLayerEventArgs) {
            tempLayerID = createTempLayerEventArgs.result.newResourceID;
            //创建地图控件
            map = new SuperMap.Map("map", {controls: [
                new SuperMap.Control.ScaleLine(),
                new SuperMap.Control.Zoom(),
                new SuperMap.Control.Navigation({
                    dragPanOptions: {
                        enableKinetic: true
                    }
                })]
            });

            //创建 TiledDynamicRESTLayer
            layer = new SuperMap.Layer.TiledDynamicRESTLayer("World", url, {transparent: true, cacheEnabled: false, redirect: true, layersID: tempLayerID}, {maxResolution: "auto", bufferImgCount: 0});
            layer.bufferImgCount = 0;
            layer.events.on({"layerInitialized": addLayer});
        }

        //显示错误信息
        function createTempLayerFailed(result){
            alert(result.error.errorMsg);
        }

        function addLayer() {
            var center = new SuperMap.LonLat(117, 40);
            map.addLayers([layer]);
            map.setCenter(center, 0);
        }

        //通过子图层layersID可见性控制
        function setLayerStatus() {
            var zTree = $.fn.zTree.getZTreeObj("tree"),
                    checkCount = zTree.getCheckedNodes(true);
            var checkLength = checkCount.length;

            //通过layersID 控制图层的显示和隐藏   目前iserver还有问题
            var str = "[0:";
            for(var i = 0; i<checkLength; i++){
                if(checkCount[i].isChild){
                    if(i<checkLength){
                        str += (checkCount[i].pId -1).toString() +"."+ checkCount[i].layerID.toString();
                    }
                    if(i<(checkLength -1)){
                        str += ",";
                    }
                }
            }

            str += "]";
            //当所有图层都不可见时
            if(str.length<5)
            {
                str = "[]";
            }
            layer.params.layersID = str;
            layer.redraw();
        }

        function showWindow() {
            if(document.getElementById("popupWin")) {
                $("#popupWin").css("display", "block");
            } else {
                $("<div id='popupWin'></div>").addClass("popupWindow").appendTo($("#result"));
            }
            $("#popupWin").css("display", "none");
            var str = "";
            str += '<div class="winTitle" onMouseDown="startMove(this,event)" onMouseUp="stopMove(this,event)"><span class="title_left">京津地区地图</span><span class="title_right"><a href="javascript:closeWindow()" title="关闭窗口">关闭</a></span><br style="clear:right"/></div>';  //标题栏

            str += '<div class="winContent" style="overflow-y:auto;height:440px;">';
            str += '<ul id="tree" class="ztree"></ul>';
            str += '</div>';
            $("#popupWin").html(str);
            document.getElementById("popupWin").style.width = "260px";
            document.getElementById("popupWin").style.height = "472px";
        }
        window.closeWindow = function(){
            $("#popupWin").css("display", "none");
        };
        window.startMove = function(o,e){
            var wb;
            if(SuperMap.Browser.name === "msie" && e.button === 1) wb = true;
            else if(e.button === 0) wb = true;
            if(wb){
                var x_pos = parseInt(e.clientX-o.parentNode.offsetLeft);
                var y_pos = parseInt(e.clientY-o.parentNode.offsetTop);
                if(y_pos<= o.offsetHeight){
                    document.documentElement.onmousemove = function(mEvent){
                        var eEvent = (SuperMap.Browser.name === "msie")?event:mEvent;
                        o.parentNode.style.left = eEvent.clientX-x_pos+"px";
                        o.parentNode.style.top = eEvent.clientY-y_pos+"px";
                    }
                }
            }
        };
        window.stopMove = function(o,e){
            document.documentElement.onmousemove = null;
        };
        function show(){
            $("#popupWin").css("display", "block");
        }
    </script>
</head>
<body onload="getLayersInfo()">
<div id='result' class='container'>
</div>
<div id="toolbar">
    <input type="button" class="btn" value="图层组控制" onclick="show()" />
</div>

<div id="map"></div>
</body>
</html>
